package com.say.utils.weixin;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Element;

import com.say.framework.core.util.PropertiesUtil;
import com.say.framework.idworker.IdWorker;
import com.say.utils.DateHelper;
import com.say.utils.SysParentFile;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;



public class ImageUtil {

    /**
     * 重新设置图像大小
     * @param sfile 图片源文件
     * @param tfile 目标文件
     * @param newWidth 新宽度
     * @param newHeight 新高度
     * @param quality 质量系数
     * @throws IOException
     */
	public static void resizeImg(String sfile, String tfile, int newWidth,
            int newHeight, float quality) throws IOException {
        if(quality > 1) {  
            throw new IllegalArgumentException(  
                    "Quality has to be between 0 and 1");  
        }

        if(newWidth <=0 || newHeight<=0) {
            throw new IllegalArgumentException(  
                    "Width or Height must greater than zero");
        }

        Image srcImg = new ImageIcon(sfile).getImage();
        Image resizedImage = srcImg.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

        Image temp = new ImageIcon(resizedImage).getImage();  

        BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.createGraphics();  

        g.setColor(Color.white);  
        g.fillRect(0, 0, newWidth, newHeight);  
        g.drawImage(temp, 0, 0, null);  
        g.dispose();  

        // Soften.  
        float softenFactor = 0.05f;  
        float[] softenArray = { 0, softenFactor, 0, softenFactor,  
                1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };  
        Kernel kernel = new Kernel(3, 3, softenArray);  
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);  
        bufferedImage = cOp.filter(bufferedImage, null);

        // Write the jpeg to a file.  
        FileOutputStream out = null;

        try {
            out = new FileOutputStream(tfile);  
            saveAsJPEG(100, bufferedImage, quality, out);  
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }
	
	 /** 
     * 以JPEG编码保存图片 
     * @param dpi  分辨率 
     * @param image_to_save  要处理的图像图片 
     * @param JPEGcompression  压缩比 
     * @param fos 文件输出流 
     * @throws IOException 
     */  
    public static void saveAsJPEG(Integer dpi ,BufferedImage image_to_save, float JPEGcompression, FileOutputStream fos) throws IOException {  
            
        //useful documentation at http://docs.oracle.com/javase/7/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html  
        //useful example program at http://johnbokma.com/java/obtaining-image-metadata.html to output JPEG data  
        
        //old jpeg class  
        //com.sun.image.codec.jpeg.JPEGImageEncoder jpegEncoder  =  com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(fos);  
        //com.sun.image.codec.jpeg.JPEGEncodeParam jpegEncodeParam  =  jpegEncoder.getDefaultJPEGEncodeParam(image_to_save);  
        
        // Image writer  
//      JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();  
        ImageWriter imageWriter  =   ImageIO.getImageWritersBySuffix("jpg").next();  
        ImageOutputStream ios  =  ImageIO.createImageOutputStream(fos);  
        imageWriter.setOutput(ios);  
        //and metadata  
        IIOMetadata imageMetaData  =  imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);  
           
           
        if(dpi !=  null && !dpi.equals("")){  
               
             //old metadata  
            //jpegEncodeParam.setDensityUnit(com.sun.image.codec.jpeg.JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);  
            //jpegEncodeParam.setXDensity(dpi);  
            //jpegEncodeParam.setYDensity(dpi);  
        
            //new metadata  
            Element tree  =  (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");  
            Element jfif  =  (Element)tree.getElementsByTagName("app0JFIF").item(0);  
            jfif.setAttribute("Xdensity", Integer.toString(dpi) );  
            jfif.setAttribute("Ydensity", Integer.toString(dpi));  
               
        }  
        
        
        if(JPEGcompression >= 0 && JPEGcompression <= 1f){  
        
            //old compression  
            //jpegEncodeParam.setQuality(JPEGcompression,false);  
        
            // new Compression  
            JPEGImageWriteParam jpegParams  =  (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();  
            jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);  
            jpegParams.setCompressionQuality(JPEGcompression);  
        
        }  
        
        //old write and clean  
        //jpegEncoder.encode(image_to_save, jpegEncodeParam);  
        
        //new Write and clean up  
        imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);  
        ios.close();  
        imageWriter.dispose();  
        
    }


    /**
     * 
    * @param templateUrl
    * @param headUrl
    * @param day
    * @param lxDay
    * @return
    * @throws Exception
    * 创建人：ZhangCaibao 
    * 2017年8月9日 上午9:28:19 
    * @String
     */
    public static String  hechengDaka(String templateUrl,String headUrl) throws Exception{
    	File path = null;
 	    try {
 	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
 	    } catch (FileNotFoundException e) {
 	    	e.printStackTrace();
 	    }
    	String savePath=SysParentFile.getParentFile();
    	//String savePath ="D://haibao";
    	
    	// 当前日期(按月保存)
    	String date = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
    	String savePath_date = savePath +  date+"/";
    	// 创建文件夹
    	File f = new File(savePath_date);
    	if (!f.exists()) {
    		f.mkdirs();
    	}
    	
    	//读取模板
    	BufferedImage template = ImgBean.loadImageLocal(savePath+templateUrl);
        String the_path =  savePath_date+IdWorker.generateId() + ".png";
        BufferedImage images_chick = ImageIO.read(new File(savePath+headUrl));
        BufferedImage imagess_output_template = ImgBean.modifyImagetogeter(images_chick, template,44,690);
		 ImgBean.writeImageLocal(the_path,  imagess_output_template);
		 return the_path.replaceAll(savePath, "");
    }
    
    

    
    
    
    
    
    
    /**
     * 合成扫码关注图
    * @param templateUrl  模板
    * @param headUrl   头像路径
    * @param codeUrl  二维码路径
    * @param userName 用户昵称
    * @throws Exception
    * 创建人：wuwen 
    * @String
     */
    public static String  compositeSubImg(String templateUrl,String headUrl,String codeUrl,String userName) throws Exception{
    	File path = null;
 	    try {
 	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
 	    } catch (FileNotFoundException e) {
 	    	e.printStackTrace();
 	    }
    	String savePath=SysParentFile.getParentFile();
    	 // 当前日期(按月保存)
    	 String date = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
    	 String savePath_date = savePath +  date+"/";
    	 // 创建文件夹
    	 File f = new File(savePath_date);
    	 if (!f.exists()) {
    		f.mkdirs();
    	 }
    	 String uuid=savePath_date+IdWorker.generateId()+ ".png";

    	 // 先截取图片为圆形
    	 ImageUtil.resizeImg(savePath+headUrl, uuid, 93, 93, 1.0f);
    	 int  cornerRadius  = 360;
    	 BufferedImage image = ImageIO.read(new File(uuid));
    	 int w = image.getWidth();
         int h = image.getHeight();
         BufferedImage output = new BufferedImage(w, h,BufferedImage.TYPE_INT_ARGB);
         Graphics2D g2 = output.createGraphics();
         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                 RenderingHints.VALUE_ANTIALIAS_ON);
         g2.setColor(Color.WHITE);
         g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius,
                 cornerRadius));
         g2.setComposite(AlphaComposite.SrcAtop);
         g2.drawImage(image, 0, 0, null);
         g2.dispose();
         
     	 // 先截取图片为正方形
     	 String code=savePath_date+IdWorker.generateId()+ ".png";
     	 // 先截取图片为正方形
     	 ImageUtil.resizeImg(savePath+codeUrl, code, 127, 127, 1.0f);
     	 int  cornerRadius1  = 0;
     	 BufferedImage image1 = ImageIO.read(new File(code));
     	
     	 int w1 = image1.getWidth();
         int h1 = image1.getHeight();
         BufferedImage output1 = new BufferedImage(w1, h1,
                  BufferedImage.TYPE_INT_ARGB);
         Graphics2D g3 = output1.createGraphics();
    
         g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                  RenderingHints.VALUE_ANTIALIAS_ON);
         g3.setColor(Color.WHITE);
         g3.fill(new RoundRectangle2D.Float(0, 0, w1, h1, cornerRadius1,
                  cornerRadius1));
         g3.setComposite(AlphaComposite.SrcAtop);
         g3.drawImage(image1, 0, 0, null);

         g3.dispose();
         
    	//读取模板
    	BufferedImage template = ImgBean.loadImageLocal(savePath+templateUrl);
    	String the_path =  savePath_date+ IdWorker.generateId() + ".png";
    	//合成圆
    	BufferedImage  output_template=  ImgBean.modifyImagetogeter(output, template,33,31);
    	//合成圆
    	output_template=  ImgBean.modifyImagetogeter(output1, output_template,337,872);
    	ImgBean.modifyImage(output_template,userName,140,90,new Color(255,255,255),new Font("微软雅黑", Font.PLAIN, 31));//???需要改坐标
    	ImgBean.writeImageLocal(the_path,  output_template);
    	return the_path.replaceAll(savePath, "");
    }
    
    
    
    /**
        *   期末引流活动-开发需求文档
    * @param templateUrl  模板
    * @param headUrl   头像路径
    * @param codeUrl  二维码路径
    * @throws Exception
        *  创建人：wuwen 
    * @String
     */
    public static String  compositeTerminalImg(String templateUrl,String headUrl,String codeUrl) {
    	try {
        	File path = null;
     	    try {
     	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
     	    } catch (FileNotFoundException e) {
     	    	e.printStackTrace();
     	    }
        	String savePath=SysParentFile.getParentFile();
	    	 // 当前日期(按月保存)
	    	 String date = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
	    	 String savePath_date = savePath +  date+"/";
	    	 // 创建文件夹
	    	 File f = new File(savePath_date);
	    	 if (!f.exists()) {
	    		f.mkdirs();
	    	 }
	    	 String uuid=savePath_date+IdWorker.generateId()+ ".png";

	    	 //如果没有用户头像，则用小塾logo
	    	 if(StringUtils.isEmpty(headUrl)){
	    	     headUrl = savePath+"/images/favicon.png";
             }
	    	 // 先截取图片为圆形
	    	 ImageUtil.resizeImg(savePath+headUrl, uuid, 226, 226, 0.3f);
	    	 int  cornerRadius  = 360;
	    	 BufferedImage image = ImageIO.read(new File(uuid));
	    	 int w = image.getWidth();
	         int h = image.getHeight();
	         BufferedImage output = new BufferedImage(w, h,BufferedImage.TYPE_INT_ARGB);
	         Graphics2D g2 = output.createGraphics();
	         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
	                 RenderingHints.VALUE_ANTIALIAS_ON);
	         g2.setColor(Color.WHITE);
	         g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius,
	                 cornerRadius));
	         g2.setComposite(AlphaComposite.SrcAtop);
	         g2.drawImage(image, 0, 0, null);
	         g2.dispose();
	         
	     	 // 先截取图片为正方形
	     	 String code=savePath_date+IdWorker.generateId()+ ".png";
	     	 // 先截取图片为正方形
	     	 ImageUtil.resizeImg(savePath+codeUrl, code, 181, 181, 1.0f);
	     	 int  cornerRadius1  = 0;
	     	 BufferedImage image1 = ImageIO.read(new File(code));
	     	
	     	 int w1 = image1.getWidth();
	         int h1 = image1.getHeight();
	         BufferedImage output1 = new BufferedImage(w1, h1,
	                  BufferedImage.TYPE_INT_ARGB);
	         Graphics2D g3 = output1.createGraphics();
	    
	         g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
	                  RenderingHints.VALUE_ANTIALIAS_ON);
	         g3.setColor(Color.WHITE);
	         g3.fill(new RoundRectangle2D.Float(0, 0, w1, h1, cornerRadius1,
	                  cornerRadius1));
	         g3.setComposite(AlphaComposite.SrcAtop);
	         g3.drawImage(image1, 0, 0, null);
	
	         g3.dispose();
	         
	    	//读取模板
	    	BufferedImage template = ImgBean.loadImageLocal(savePath+templateUrl);
	    	String the_path =  savePath_date+IdWorker.generateId() + ".jpg";
	    	//合成圆
	    	BufferedImage  output_template=  ImgBean.modifyImagetogeter(output, template,387,190);
	    	//合成圆
	    	output_template=  ImgBean.modifyImagetogeter(output1, output_template,625,1509);
	    	ImgBean.writeImageLocal(the_path,  output_template);
	    	return the_path.replaceAll(savePath, "");
    	} catch (Exception e) {
    		e.printStackTrace();
		}
    	return "";
    }
    

  
}